<template>


  <!-- 列表 -->
  <ContentWrap>

    <el-container class="layout-container">
      <el-aside class="left" :style="{ width: leftWidth + 'px' }">
        <el-input v-model="filterText" style="width: 240px" placeholder="Filter keyword">
          <template #append>
            <el-button @click="toggleExpandAll">
              <el-icon>
                <DCaret />
              </el-icon>

            </el-button>
          </template>
        </el-input>


        <el-tree ref="treeRef" v-loading="loading" :data="list" draggable node-key="id" @node-drag-end="handleDragEnd"
          :filter-node-method="filterNode" @node-click="handleNodeClick" :stripe="true" :show-overflow-tooltip="true"
          row-key="id" :props="treeProps" :default-expand-all="isExpandAll" v-if="refreshTable" />

      </el-aside>
      <div class="resize" @mousedown="startDrag"></div>
      <el-container class="right editor-right" :style="{ width: rightWidth + 'px' }">
        <el-header style="text-align: right; font-size: 12px">
          <div class="toolbar">
            <!-- 搜索工作栏 -->
            <el-form :model="queryParams" ref="queryFormRef" :inline="true"     size="small"        >
              <el-form-item>
                <el-input v-model="currentNodeDataRef.name" placeholder="Filter keyword" >


                  <template #append>
                    
                <el-button type="primary" plain @click="openForm('create', 0)"
                  v-hasPermi="['infra:demo02-category:create']">
                  <Icon icon="ep:folder-add" class="mr-5px" />

                </el-button>

                <el-button type="primary" plain @click="openForm('create', 1)"
                  v-hasPermi="['infra:demo02-category:create']">
                  <Icon icon="ep:document-add" class="mr-5px" />
                </el-button>

                <el-button @click="handleQuery">
                  <Icon icon="ep:refresh" class="mr-5px" />
                </el-button>

                <el-button @click="handleSave">
                  <Icon icon="fa:save" class="mr-5px" />
                </el-button>
       </template>

                </el-input>
              </el-form-item>


            </el-form>
          </div>
        </el-header>
        <el-main>
          <el-input v-model="currentNodeDataRef.sourceCode" style="width: 100%;height: 300px"
            :autosize="{ minRows: 20 }" type="textarea" placeholder="Please input" />
        </el-main>
      </el-container>
    </el-container>

  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <Demo02CategoryForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { handleTree } from '@/utils/tree'
import download from '@/utils/download'
import * as Demo02CategoryApi from '@/api/infra/demo/demo02'
import Demo02CategoryForm from './Demo02CategoryForm.vue'
import * as Demo01ContactApi from '@/api/infra/demo/demo01'
import { ref, watch } from 'vue'
import { ElTree } from 'element-plus'
import {compileCode} from "@/views/infra/codegen/sfc/sfc-compiler.js";


defineOptions({ name: 'Demo02Category' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const textarea1 = ref('')

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const queryParams = reactive({
  name: null,
  pid: null,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const treeProps = {
  label: 'name'      // 使用 title 字段作为 label

};

const currentNodeDataRef = ref({
  name: "",
  compileJs:"",
  compileCss:"",
  type: 0,
  id: "",
  pid: "", 
  sourceCode: "" // 初始化为空字符串

})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    console.log('queryParams ==== > ', queryParams)
    const data = await Demo02CategoryApi.getCmpPage(queryParams)
    list.value = handleTree(data.list, 'id', 'pid')
  } finally {
    loading.value = false
  }
}


const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()


watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}

const handleNodeClick = async (data, node) => {
  console.log('节点被点击:', data);
  console.log('节点组件:', node);
  const res = await Demo02CategoryApi.getCmp(data.id)
  currentNodeDataRef.value = res;
};


const handleDragEnd = async (
  draggingNode: Node,
  dropNode: Node,
  dropType: NodeDropType,
  ev: DragEvents
) => {
  console.log('tree drag end:', draggingNode && draggingNode.label, dropNode && dropNode.label, dropType)
  draggingNode.data.pid = dropNode?.data?.id;
  currentNodeDataRef.value = draggingNode.data;
  await Demo02CategoryApi.updateCmp(currentNodeDataRef.value)
  getList()

}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const handleSave = async () => {
  console.log('保存按钮被点击');

  const { compileJs, compileCss } = compileCode(currentNodeDataRef.value.sourceCode)

  console.log('编译后的JS:', compileJs);
  console.log('编译后的CSS:', compileCss);
  currentNodeDataRef.value.compileJs = compileJs;
  currentNodeDataRef.value.compileCss = compileCss;

  await Demo02CategoryApi.updateCmp(currentNodeDataRef.value)
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, cmpType: number, id?: string) => {
  formRef.value.open(type, cmpType, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await Demo02CategoryApi.deleteDemo02Category(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 展开/折叠操作 */
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const toggleExpandAll = async () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  await nextTick()
  refreshTable.value = true
}

/** 初始化 **/
onMounted(() => {
  window.addEventListener('resize', () => {
    rightWidth.value = window.innerWidth - leftWidth.value - 10;
  });

  getList()

})

const leftWidth = ref(200); // 左侧宽度
const rightWidth = ref(window.innerWidth - 210); // 右侧宽度（总宽度 - 左侧宽度 - 拖动条宽度）

const startDrag = (e: MouseEvent) => {
  const startX = e.clientX;
  const initialLeftWidth = leftWidth.value;

  const handleMouseMove = (e: MouseEvent) => {
    const newLeftWidth = initialLeftWidth + (e.clientX - startX);
    if (newLeftWidth < 100) return; // 最小宽度限制
    leftWidth.value = newLeftWidth;
    rightWidth.value = window.innerWidth - newLeftWidth - 10; // 更新右侧宽度
  };

  const handleMouseUp = () => {
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  };

  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};


</script>
<style lang="css" scoped>
.layout-container {
  display: flex;
  width: 100%;
  height: 100vh;
}
.toolbar {
  padding:8px;
}
.editor-right .el-header{
  margin: 0;
  height: auto;
}

.toolbar .el-form--inline .el-form-item {
  margin: 0;
}
.el-form--inline .el-form-item {
  margin: 0;
}
.left {
  background: var(--el-color-primary-light-8);
  overflow: hidden;
}

.resize {
  width: 10px;
  cursor: col-resize;
  background-color: #d6d6d6;
  user-select: none;
}

.right {
  flex-grow: 1;
  overflow: hidden;
  background: #fff;
}

.el-header {
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}
</style>